﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace CustomAuthorization
{
    public class JwtHelper
    {
        public string GenerateJwt()
        {
            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.NameIdentifier, "6"));
            claims.Add(new Claim(ClaimTypes.Name, "wja"));
            claims.Add(new Claim(ClaimTypes.Role, "User"));
            claims.Add(new Claim(ClaimTypes.Role, "Admin"));
            claims.Add(new Claim("PassPort", "E90000082"));
            string key = "absdfdsfd@#423434ERsadandafsdafFdsfasdfasd2434%$#@fa";
            DateTime expires = DateTime.Now.AddDays(1);
            byte[] secBytes = Encoding.UTF8.GetBytes(key);
            var secKey = new SymmetricSecurityKey(secBytes);
            var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
            var tokenDescription = new JwtSecurityToken(claims: claims, expires: expires, signingCredentials: credentials);
            string jwt = new JwtSecurityTokenHandler().WriteToken(tokenDescription);
            Console.WriteLine(jwt);
            return jwt;
        }

        public void DecryptJwt(string jwt)
        {
            string[] segments = jwt.Split('.');
            string header = JwtDecode(segments[0]);
            string payload = JwtDecode(segments[1]);
            Console.WriteLine("-------------------------head-------------------------------");
            Console.WriteLine(header);
            Console.WriteLine("-------------------------payload-------------------------------");
            Console.WriteLine(payload);
        }


        private string JwtDecode(string jwt)
        {
            jwt = jwt.Replace('-', '+').Replace('_', '/');
            switch (jwt.Length % 4)
            {
                case 2: jwt += "=="; break;
                case 3: jwt += "="; break;
            }
            var bytes = Convert.FromBase64String(jwt);
            return Encoding.UTF8.GetString(bytes);
        }

        /// <summary>
        /// 使用先验证前面然后解密的方式进行解密jwt
        /// </summary>
        /// <param name="jwt"></param>
        public void Decrypt(string jwt)
        {
            string key = "absdfdsfd@#423434ERsadandafsdafFdsfasdfasd2434%$#@fa";
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            TokenValidationParameters validationParameters = new TokenValidationParameters();
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            validationParameters.IssuerSigningKey = securityKey;
            validationParameters.ValidateIssuer = false;
            validationParameters.ValidateAudience = false;
            ClaimsPrincipal principal = handler.ValidateToken(jwt, validationParameters, out SecurityToken secToken);
            foreach (var kvp in principal.Claims)
            {
                Console.WriteLine($"{kvp.Type} = {kvp.Value}");
            }
        }
    }
}
